<?php

namespace app\api\model;

use app\common\enums\StatusEnum;

class OauthWatchLog extends \app\common\model\OauthWatchLog
{
    /**
     * 添加我的轨迹记录
     * @param $oauthId
     * @param $fileId
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public static function addOne($oauthId, $fileId)
    {
        // 删除7天前的数据
        $day7 = strtotime('-7 days');
        OauthWatchLog::where('create_time', '<=', $day7)->delete();

        // 查看近7天记录
        $log = self::where(['oauth_id' => $oauthId, 'file_id' => $fileId])->find();
        if (empty($log)) {
            // 添加新的记录
            $log = new OauthWatchLog();
            $log->create_time = time();
        }

        $log->oauth_id = $oauthId;
        $log->file_id = $fileId;
        $log->update_time = time();
        $log->save();
    }

    /**
     * 我的轨迹列表
     * @param int $oauthId
     * @param int $type 1视频 2音频 3学习资料课件下载
     * @param int $page 第几页
     * @param int $size 每页显示条数
     * @return array
     * @throws \think\Exception\DbException
     */
    public static function getList($oauthId, $type, $page, $size)
    {
        $offset = ($page - 1) * $size;
        $sql = static::field('f.id AS fileId,f.class_id AS classId, f.course_type AS courseType, f.file_name AS fileName, f.video_img AS videoImg, f.create_time AS createTime,o.lang_id AS langId')
            ->alias('l')
            ->join('lang_class_file f', 'l.file_id = f.id')
            ->join('lang_class o', 'f.class_id = o.id')
            ->where([
                'l.oauth_id' => $oauthId,
                'f.type' => $type,
                'f.status' => StatusEnum::ENABLED
            ]);

        $model = $sql->order(['l.create_time' => 'desc'])
            ->limit($offset, $size)
            ->select()
            ->toArray();

        foreach ($model as $key => $value) {
            $model[$key]['createTime'] = date('Y-m-d', $value['createTime']);
            $model[$key]['videoImg'] = $value['videoImg'] ? config('file_prefix') . $value['videoImg'] : '';
        }

        return [
            'list' => $model,
            'count' => $sql->count()
        ];
    }
}